package com.zz.chenko.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 聊天机器人工具类
 *
 * @author Zhong
 * @since 2016年12月12日
 */
public class ChatRobotUtil {


    public static String getRequest(String message) throws Exception {
        String apiKey = "6adc52db49eb4e41aea26f0d86507dde";
        String info = URLEncoder.encode(message, "utf-8");// 这里可以输入问题
        String getURL = "http://www.tuling123.com/openapi/api?key=" + apiKey + "&info=" + info;
        URL getUrl = new URL(getURL);
        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
        connection.connect();

        // 取得输入流，并使用Reader读取
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        // 断开连接
        connection.disconnect();
        System.out.println(info);
        System.out.println(sb.toString());
        return sb.toString();
    }

    public static void main(String[] args) {
        try {
            String s = getRequest("成语接龙地大物博");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
